package com.spotalog.server.service.search;

import static com.spotalog.shared.model.Address.ADDRESS;
import static com.spotalog.shared.model.Address.CITY;
import static com.spotalog.shared.model.Address.COUNTRY;
import static com.spotalog.shared.model.Address.STATE;
import static com.spotalog.shared.model.Address.ZIPCODE;
import static com.spotalog.shared.model.DatastoreObject.DATE_ALTERED;
import static com.spotalog.shared.model.DatastoreObject.DATE_CREATED;
import static com.spotalog.shared.model.Spot.DESCRIPTION;
import static com.spotalog.shared.model.Spot.LOCATION;
import static com.spotalog.shared.model.Spot.NAME;
import static com.spotalog.shared.model.Spot.TYPE;

import javax.inject.Inject;

import com.google.appengine.api.search.Document;
import com.google.appengine.api.search.GeoPoint;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.spotalog.shared.model.Address;
import com.spotalog.shared.model.Location;
import com.spotalog.shared.model.Spot;

class SpotToDocument extends DocumentConverter implements Function<Spot, Document> {
	@Inject
	SpotToDocument() {
		super(Spot.class);
	}

	@Override
	public Document apply(Spot spot) {
		Document.Builder doc = document(spot.getId());
		if (!Strings.isNullOrEmpty(spot.getName())) {
			doc.addField(field(NAME).setText(spot.getName()));
		}
		if (!Strings.isNullOrEmpty(spot.getDescription())) {
			doc.addField(field(DESCRIPTION).setText(spot.getDescription()));
		}
		if (spot.getDateAltered() != null) {
			doc.addField(field(DATE_ALTERED).setDate(spot.getDateAltered()));
		}
		if (spot.getDateCreated() != null) {
			doc.addField(field(DATE_CREATED).setDate(spot.getDateCreated()));
		}
		if (spot.getType() != null) {
			doc.addField(field(TYPE).setAtom(spot.getType().toString()));
		}
		Address address = spot.getAddress();
		if (address != null) {
			if (!Strings.isNullOrEmpty(address.getAddress())) {
				doc.addField(field(ADDRESS).setText(address.getAddress()));
			}
			if (!Strings.isNullOrEmpty(address.getCity())) {
				doc.addField(field(CITY).setText(address.getCity()));
			}
			if (!Strings.isNullOrEmpty(address.getState())) {
				doc.addField(field(STATE).setText(address.getState()));
			}
			if (!Strings.isNullOrEmpty(address.getZipcode())) {
				doc.addField(field(ZIPCODE).setText(address.getZipcode()));
			}
			if (!Strings.isNullOrEmpty(address.getCountry())) {
				doc.addField(field(COUNTRY).setText(address.getCountry()));
			}
		}

		Location location = spot.getLocation();
		if (location != null) {
			doc.addField(field(LOCATION).setGeoPoint(
					new GeoPoint(location.getLatitude(), location.getLongitude())));
		}
		return doc.build();
	}
}
